use std::{
    env, fs,
    path::Path,
    process,
};

use compiler::codegen;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() != 3 {
        eprintln!("用法: {} <源文件路径> <输出IR路径>", args[0]);
        process::exit(1);
    }

    let input_path = &args[1];
    let output_path = &args[2];

    let source = match fs::read_to_string(input_path) {
        Ok(content) => content,
        Err(err) => {
            eprintln!("读取源文件失败: {err}");
            process::exit(1);
        }
    };

    match codegen::compile_to_llvm_ir(&source, "module") {
        Ok(ir) => {
            let output_path_ref = Path::new(output_path);
            if let Some(parent) = output_path_ref.parent() {
                if !parent.as_os_str().is_empty() {
                    if let Err(err) = fs::create_dir_all(parent) {
                        eprintln!("创建输出目录失败: {err}");
                        process::exit(1);
                    }
                }
            }
            if let Err(err) = fs::write(output_path_ref, ir) {
                eprintln!("写入 IR 文件失败: {err}");
                process::exit(1);
            }
        }
        Err(err) => {
            eprintln!("生成 LLVM IR 失败: {err}");
            process::exit(1);
        }
    }
}
